package com.chen.aiagent.tools;

import com.chen.aiagent.constant.EmailConstant;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeBodyPart;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import java.io.File;
import java.util.Properties;

/**
 * @author 陈奥
 */
public class EmailTool {

    private final String smtpHost;

    private final int smtpPort;

    private final String fromEmail;

    private final String password;

    private final boolean useTLS;

    public EmailTool(String smtpHost, int smtpPort, String fromEmail, String password, boolean useTLS) {
        this.smtpHost = smtpHost;
        this.smtpPort = smtpPort;
        this.fromEmail = fromEmail;
        this.password = password;
        this.useTLS = useTLS;
    }

    public String sendEmail(
            @ToolParam(description = "Recipient email address(es), comma separated for multiple") String toEmail,
            @ToolParam(description = "Email subject") String subject,
            @ToolParam(description = "Email body content") String body
    ) {
        try {
            // 配置SMTP服务器属性
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");

            // 根据端口判断使用SSL还是TLS
            if (smtpPort == 465) {
                // 465端口使用SSL
                props.put("mail.smtp.socketFactory.port", smtpPort);
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.socketFactory.fallback", "false");
            } else {
                // 其他端口使用TLS
                props.put("mail.smtp.starttls.enable", useTLS);
            }

            props.put("mail.smtp.host", smtpHost);
            props.put("mail.smtp.port", smtpPort);

            // 创建邮件会话
            Session session = Session.getInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(fromEmail, password);
                }
            });

            // 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromEmail));

            // 设置收件人（支持多个收件人）
            String[] recipients = toEmail.split(",");
            for (String recipient : recipients) {
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.trim()));
            }

            message.setSubject(subject);
            message.setText(body);

            // 发送邮件
            Transport.send(message);

            return "Email sent successfully to: " + toEmail;

        } catch (MessagingException e) {
            return "Error sending email: " + e.getMessage();
        } catch (Exception e) {
            return "Unexpected error: " + e.getMessage();
        }
    }

    @Tool(description = "Send HTML email with rich content")
    public String sendHtmlEmail(
            @ToolParam(description = "Recipient email address(es)") String toEmail,
            @ToolParam(description = "Email subject") String subject,
            @ToolParam(description = "HTML email body content") String htmlBody,
            @ToolParam(description = "Plain text fallback content") String textBody
    ) {
        try {
            // 配置SMTP服务器属性
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");

            // 根据端口判断使用SSL还是TLS
            if (smtpPort == 465) {
                // 465端口使用SSL
                props.put("mail.smtp.socketFactory.port", smtpPort);
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.socketFactory.fallback", "false");
            } else {
                // 其他端口使用TLS
                props.put("mail.smtp.starttls.enable", useTLS);
            }

            props.put("mail.smtp.host", smtpHost);
            props.put("mail.smtp.port", smtpPort);

            // 创建邮件会话
            Session session = Session.getInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(fromEmail, password);
                }
            });

            // 创建HTML邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromEmail));

            // 设置收件人
            String[] recipients = toEmail.split(",");
            for (String recipient : recipients) {
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.trim()));
            }

            message.setSubject(subject);

            // 设置HTML内容和纯文本备用内容
            Multipart multipart = new MimeMultipart("alternative");

            // 添加纯文本部分
            BodyPart textPart = new MimeBodyPart();
            textPart.setText(textBody);
            multipart.addBodyPart(textPart);

            // 添加HTML部分
            BodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(htmlBody, "text/html; charset=utf-8");
            multipart.addBodyPart(htmlPart);

            message.setContent(multipart);

            // 发送邮件
            Transport.send(message);

            return "HTML email sent successfully to: " + toEmail;

        } catch (MessagingException e) {
            return "Error sending HTML email: " + e.getMessage();
        } catch (Exception e) {
            return "Unexpected error: " + e.getMessage();
        }
    }

    @Tool(description = "Send email with file attachment")
    public String sendEmailWithAttachment(
            @ToolParam(description = "Recipient email address(es)") String toEmail,
            @ToolParam(description = "Email subject") String subject,
            @ToolParam(description = "Email body content") String body,
            @ToolParam(description = "File path to attach") String attachmentPath
    ) {
        try {
            // 配置SMTP服务器属性
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");

            // 根据端口判断使用SSL还是TLS
            if (smtpPort == 465) {
                // 465端口使用SSL
                props.put("mail.smtp.socketFactory.port", smtpPort);
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.socketFactory.fallback", "false");
            } else {
                // 其他端口使用TLS
                props.put("mail.smtp.starttls.enable", useTLS);
            }

            props.put("mail.smtp.host", smtpHost);
            props.put("mail.smtp.port", smtpPort);

            // 创建邮件会话
            Session session = Session.getInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(fromEmail, password);
                }
            });

            // 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromEmail));

            // 设置收件人
            String[] recipients = toEmail.split(",");
            for (String recipient : recipients) {
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.trim()));
            }

            message.setSubject(subject);

            // 创建多部分消息
            Multipart multipart = new MimeMultipart();

            // 添加邮件正文
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            multipart.addBodyPart(messageBodyPart);

            // 添加附件
            BodyPart attachmentPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachmentPath);
            attachmentPart.setDataHandler(new DataHandler(source));
            attachmentPart.setFileName(new File(attachmentPath).getName());
            multipart.addBodyPart(attachmentPart);

            message.setContent(multipart);

            // 发送邮件
            Transport.send(message);

            return "Email with attachment sent successfully to: " + toEmail;

        } catch (MessagingException e) {
            return "Error sending email with attachment: " + e.getMessage();
        } catch (Exception e) {
            return "Unexpected error: " + e.getMessage();
        }
    }
} 